import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:app_settings/app_settings.dart';
import 'package:http/http.dart' as http;
import 'package:path_provider/path_provider.dart';

import '../tool/network_status.dart';
import '../tool/tool.dart';

const String baseUrl = 'http://47.253.203.212/';
// const String baseUrl = 'https://www.baidu.com';
///如果没有网络，弹出提示框，到设置检查
Future<bool> networkStatus() async {
  bool isConnected = await listenNetworkStatus();

  if (isConnected == false) {
    openCupertinoDialog('You don\'t seem to have an internet connection, are you sure to check?', () async {
      AppSettings.openAppSettings(type: AppSettingsType.wifi);
    });
    return false;
  }
  return true;
}

///请求OTA下载链接
Future<Map<String, dynamic>?> checkOTA(String ssid) async {
  if (await networkStatus() == false) {
    return null;
  }
  try {
    ///get请求方法1
    //final response = await http.get(Uri.parse('${baseUrl}v1/app/getOTAVersion'));

    ///get请求带参数的方法2
    //  final uri = Uri.https('example.com', '/api', {
    //   'param1': 'value1',
    //   'param2': 'value2',
    // });

    // final response = await http.get(uri);
    String api = 'v1/app/getOTAVersion';
    // String api = '';

    final response = await http.post(Uri.parse('${baseUrl}$api'),
        headers: <String, String>{
          'Content-Type': 'application/json; charset=UTF-8',
        },
        body: jsonEncode(<String, String>{
          'OTAType': ssid,
        }));
    print('开始请求======> ${response.request?.url}');

    if (response.statusCode == 200) {
      // 强制使用 UTF-8 解码
      var utf8Body = utf8.decode(response.bodyBytes);
      var data = json.decode(utf8Body) as Map<String, dynamic>;
      print('object');
      print('data:=======> ${jsonEncode(data)}');
      return data;
    } else {
      String text = 'code : ${response.statusCode}\n error : ${response.reasonPhrase}';
      toast(text);
      throw Exception(
          'Faild to load v1/app/getOTAVersion \n code : ${response.statusCode}\n error : ${response.reasonPhrase}');
    }
  } catch (e) {
    // toast('${e}');
    String error = 'You don\'t have network access, are you sure to check?';
    openCupertinoDialog(error, () async {
      AppSettings.openAppSettings(type: AppSettingsType.settings);
    });
    print('Exception:  $e');
    return null;
  }
}

///下载文件，并且读取
Future<Uint8List?> downloadFile(String url, String fileName) async {
  try {
    // 发送 GET 请求以下载文件
    final response = await http.get(Uri.parse(url));

    if (response.statusCode == 200) {
      // 获取应用程序的临时目录
      final directory = await getTemporaryDirectory();

      // 定义文件路径
      final filePath = '${directory.path}/$fileName';
      // 将文件写入本地存储
      final file = File(filePath);
      await file.writeAsBytes(response.bodyBytes);
      log('文件已存到本地: $filePath');

      return response.bodyBytes;
      // ignore: dead_code

      // 读取文件内容
      final fileContent = await file.readAsString();
      print('文件内容: $fileContent');
    } else {
      print('文件下载失败，状态码: ${response.statusCode}');
      return null;
    }
  } catch (e) {
    print('下载或读取文件时发生错误: $e');
    return null;
  }
}
